package com.qingke.easyjava.springhibernate.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.qingke.easyjava.springhibernate.bean.Category;
import com.qingke.easyjava.springhibernate.bean.Expense;
import com.qingke.easyjava.springhibernate.service.ExpenseService;

public class ExpenseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        WebApplicationContext wac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServletContext());
        ExpenseService service = wac.getBean(ExpenseService.class);

        Expense dummyExpense = new Expense();
        dummyExpense.setAmount(Math.random() * 100);
        dummyExpense.setDate(new Date());
        dummyExpense.setMemo("Dummy Expense");
        
        Category category = service.getCategoryByCode("N/A");
        dummyExpense.setCategory(category);
        service.saveExpense(dummyExpense);

        // write the output string to stream
        OutputStream os = resp.getOutputStream();
        os.write("Success".getBytes());
        os.flush();
        os.close();
    }
}
